#!/bin/bash

# Created by Jonathan Neitz 

# This is a handy script used to start Notebook or other
# applications that you wish to distribute in an app folder like
# structure. Simply rename this script to the name of your appfolder
# and it will exec the script called wrapper inside of it.
# This assumes that the app exe is named the same as the app folder
# but in all lower case.
#
# For example notebook is Notebook/notebook


# configuration variables used throughout the script
DOC_REQUEST=70
DIAGONSTICS_REQUEST=71
PROGRAM_NAME="Notebook Wrapper Script"
FILE_NOT_FOUND=3
SUCCESS=0
DIAGONSTICS=
QT_CORE_LIBNAME="libQtCore.so.4"
QT_GUI_LIBNAME="libQtGui.so.4"
QT_CORE_DEBUG_LIBNAME="libQtCore_debug.so.4"
QT_GUI_DEBUG_LIBNAME="libQtGui_debug.so.4"
QT_LIBRARY_PATH=
QT_LIBS="$QT_CORE_LIBNAME $QT_GUI_LIBNAME $QT_CORE_DEBUG_LIBNAME $QT_GUI_DEBUG_LIBNAME"

# This function just uppercases a string passed to it
# and returns the value in uppstr
toupper()
{
   uppstr=$(echo $1 | tr a-z A-Z)
}

# This function returns the absolute path for a path
# passed to it. The resulting path is returned in abspath
get_full_path()
{
  abspath=$(cd "$(dirname "$1")" ; pwd)
}

# This function capitalizes the first letter in a word
# the result is returned in capword
capitalize_word()
{
  capword=$(basename "$1")
  toupper ${capword:0:1}
  capword="$uppstr${capword:1}"  
}

# Print formatted output to stderr

print_error()
{
    if [ -z $DIAGNOSTICS ]; then
	printf "Error: $@" >&2
    fi
}

# Returns the exe path for an app bundle like application
# This is assumed to be of the form App/app and is determined
# from the name of the script. It also makes an attempt at handling
# most of the common ways of symlinking to this script.
# However their may still be cases where this breaks, please modify
# this script to account for this or ask that they symlink with an
# absolute path. Returns path in exe_path

find_exe_path()
{
   get_full_path "$1"
   capitalize_word "$1"
   local file=$(basename "$1")

  if [ -h "$0" ]; then         # symlinked path resolve to full path
     get_full_path "$0"
     file=$(basename "$0")
     file=$(cd "$abspath"; readlink "$file")

     if [ "${file:0:1}" = "/" ]; then
	get_full_path "$file"
     else 
     	get_full_path "$abspath/$file";
     fi

     echo "$abspath"
     file=$(basename "$file")
  fi

  capitalize_word "$file"
  exe_path="$abspath/$capword/wrapper"
  exe_real_path="$abspath/$capword/$file"
}


print_diagonstics()
{
    DIAGONSTICS=3
    echo
    echo "Notebook Diagnostics..."
    echo "============================================"
    echo "Looking for main executable at: "
    check_exefile "${exe_real_path}"
    echo "Executable Wrapper Location: "
    check_exefile "${exe_path}"
    echo "Checking for Qt libraries at: "
    echo "$QT_LIBRARY_PATH"
    verify_Qt_library_path 1
    echo "============================================"
    DIAGONSTICS=
}

get_answer()
{
    if [ $1 -eq 0 ]; then
	echo -n "Yes"
    else
	echo -n "No"
    fi
}

check_exefile()
{
    echo $'\t'"$1"
    verify_file_path "$1"
    echo $'\t'"Exists: " $(get_answer $?)
    verify_file_is_exectuable "$1"
    echo $'\t'"Is Exectuable: " $(get_answer $?)
}

verify_file_path()
{
 local exe_path="$1"
 if [ ! -f "${exe_path}" ]; then
    print_error $'\n' "Cannot find " "${exe_path}"
    return $FILE_NOT_FOUND
 fi
}

verify_file_is_exectuable()
{
 if [ ! -x "$1" ]
 then
    print_error "$1" " is not exectuable"
    return $FILE_NOT_FOUND
 fi
}

set_Qt_library_path()
{
    local LIBRARY_PATH=$(dirname "${exe_real_path}")
    QT_LIBRARY_PATH="$LIBRARY_PATH/supportlibs"
}

verify_Qt_library_path()
{
    local STATUS=0

    local FOUND_QT_LIBS=$(ls "$QT_LIBRARY_PATH" | grep libQt)

    if [ ${#FOUND_QT_LIBS} -eq 0 ]; then
	for lib in $QT_LIBS
	do
	    if [ $# -ne 0 ]; then
		echo -n $'\t' $lib
	    fi
	    if [[ ! -f "$QT_LIBRARY_PATH""/$lib" ]]; then
		if [ $# -ne 0 ]; then
		    echo $'\t'"Missing"
		fi
	    else
		if [ $# -ne 0 ]; then
		    echo $'\t' "Found"
		fi
	    fi
1
	done
	STATUS=1
    else
	if [ $# -ne 0 ]; then
	for lib in $FOUND_QT_LIBS
	do
	    if [ $# -ne 0 ]; then
		echo -n $'\t' $lib
	    fi

	    if [ $# -ne 0 ]; then
		echo $'\t' "Found"
	    fi
	done
	fi
    fi

# This is commented out
: <<EOF
    for lib in $QT_LIBS
    do
	if [ $# -ne 0 ]; then
	    echo -n $'\t' $lib
	fi

	if [[ ! -f "$QT_LIBRARY_PATH""/$lib" ]]; then
	    if [ $# -ne 0 ]; then
		echo $'\t'"Missing"
	    fi
	    STATUS=1
	else
	    if [ $# -ne 0 ]; then
		echo $'\t'"Found"
	    fi
	fi
    done
EOF

    return $STATUS
}

print_usage()
{
   cat <<EOF
Usage: $PROGRAM_NAME [options]
Options:
    -h                  Display this information
    -s --diagnostics    Print diagnostics information on $PROGRAM_NAME startup
    --set-qt-directory      Explictly set the directory for the Qt libraries
EOF
}


verify_program_bundle()
{
    RETURN_VALUE=
    verify_file_path "$exe_path"
    RETURN_VALUE=$?
    verify_file_is_exectuable "$exe_path"
    RETURN_VALUE=$?
    verify_file_path "$exe_real_path"
    RETURN_VALUE=$?
    verify_file_is_exectuable "$exe_real_path"
    RETURN_VALUE=$?

# Removed as we are now using rpath to find Qt libraries
#    verify_Qt_library_path
#    RETURN_VALUE=$?
#    if [ $RETURN_VALUE -ne 0 ]; then
#	echo "Missing Qt Libraries..."
#	verify_Qt_library_path 1
#    fi
    return $RETURN_VALUE
}

exec_program()
{
    verify_program_bundle
    if [ $? -eq 0 ]; then
	exec "$exe_path" "$@"
    else
	print_error "Failed to start %s %s\n" $(basename "$exe_real_path") "due to the previous errors"
    fi
}

#-- Start of script --

find_exe_path "$0"
set_Qt_library_path

if [ $# -eq 0 ]; then  # if no arguments just run the program
    exec_program
else
for arg in "$@"   # Check for command line parameters...
do
    case "$arg" in
    -h)
    print_usage
    exit $DOC_REQUEST
    ;;
    -s | --diagnostics)
    print_diagonstics
    ;;
    --set-qt-directory)
    #set qt directory here
    shift
    ;;
    *)
    exec_program "$@"
    ;;
    esac
done
fi


